﻿
#region Using Directives
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using System.Text;
#endregion

namespace ActiveDevelopmentEnvironment.Framework.JsonDotNet
{
    /// <summary>
    /// Encodes and decodes json objects.
    /// </summary>
    public static class Json
    {
        /// <summary>
        /// Converts the xml object to a JSON object that is ready to be sent back to the BrowserApi.
        /// </summary>
        /// <param name="CallbackMethodName">The callback function on the BrowserApi.</param>
        /// <param name="DataElement">The object with the data to convert.</param>
        /// <returns>The results as a string.</returns>
        public static string ToJson(string CallbackMethodName, IEnumerable<XElement> DataElements)
        {
            StringBuilder JsonBuilder = new StringBuilder();
            JsonBuilder.Append(CallbackMethodName);
            JsonBuilder.AppendLine("(");

            Json.WriteSubElements(JsonBuilder, DataElements);
            JsonBuilder.Remove(JsonBuilder.Length - 3, 3);

            JsonBuilder.AppendLine(");");
            return JsonBuilder.ToString();
        }

        private static void WriteSubElements(StringBuilder JsonBuilder, IEnumerable<XElement> DataElements)
        {
            JsonBuilder.AppendLine("{");
            int ElementId = 1;
            foreach (XElement DataElement in DataElements)
            {
                JsonBuilder.Append("'");
                JsonBuilder.Append(ElementId);
                JsonBuilder.Append("':'");
                JsonBuilder.Append(DataElement.Value);
                JsonBuilder.AppendLine("' ,");
                ElementId++;
            }
            JsonBuilder.Remove(JsonBuilder.Length - 3, 3);
            
            JsonBuilder.AppendLine("},");
        }
    }
}